/** \file    DebugLog.cpp
  * \brief   Serializes segments debug information.
  * \date    2002 - 2003
  * \author  Fedor Chelnokov
  * \version $Header: /home/cscom1r4/cvsroot/cs/segm/src/DebugLog.cpp,v 1.1 2004/05/20 09:11:46 cscom1r4 Exp $
  */

#include "segm/Segmentation.h"
#include <sstream>
#include <algorithm>
#include <fstream>

inline static void clear_text(Segment &g)
	{ g.text.erase(); }

inline static void appendPosInfo(Segment &g) 
{
	std::ostringstream s;
	s << 
		"pixels=" << g.pixelCount << "\n"

		"centre=(" << g.centre.x << ',' << g.centre.y << ")\n"
		
		"boundingBox=("
		"x1=" << g.boundingBox.x1 << ","
		"y1=" << g.boundingBox.y1 << ","
		"x2=" << g.boundingBox.x2 << ","
		"y2=" << g.boundingBox.y2 << ")\n"

		"meanColor=(" << g.meanColor.r << ',' << g.meanColor.g << ',' << g.meanColor.b << ")\n"
		
		"colorDispersion=" << g.colorDispersion << "\n";

	g.text += s.str();
}

void Segmentation::logSegmDebug(const std::string & debugFile)
{
	if (!debugFile.empty()) {
		std::ofstream log(debugFile.c_str(), std::ios::app);

		log << "\n%segmentation(" << count() << ",\"" << 
			m_segmImageFile << "\")\n";

		if (!m_plotFileName.empty())
			log << "%plot(\"" << m_plotFileName << "\")\n";

		size_t i;
		for (i = 0; i != count(); ++i) {
			Segment &g = segmentByIndex(i);
			log << "%segm(" << i <<
				',' << (int)g.color.r <<
				',' << (int)g.color.g <<
				',' << (int)g.color.b <<
				") " << g.text;
			if (g.text[g.text.size()-1] != '\n')
				log << '\n';
		}

		log << "%\\segmentation\n" << std::endl;
	}

	m_plotFileName.erase();
	std::for_each(segmentsBegin(), segmentsEnd(), clear_text);
}

void Segmentation::posSegmDebug()
{
	positions();
	colorStatistics();

	std::for_each(segmentsBegin(), segmentsEnd(), appendPosInfo);
}

